require 'zlib'

input_path = 'Scripts.rxdata'
output_dir = 'exported_scripts'

Dir.mkdir(output_dir) unless File.directory?(output_dir)

def safe_puts(msg)
  begin
    STDOUT.puts msg
  rescue
    begin
      STDOUT.write(msg.to_s + "\n")
    rescue
      # 最后兜底，不抛异常
    end
  end
end

File.open(input_path, 'rb') do |f|
  scripts = Marshal.load(f)
  scripts.each do |id, name, data|
    begin
      name = name.to_s
      safe_name = name.gsub(/[\/\\:\*\?"<>\|\x00-\x1F]/, "_")
      safe_name = safe_name.gsub(/[^ -~]/, "_")  # 去掉非ASCII字符

      content = Zlib::Inflate.inflate(data)
      out_path = File.join(output_dir, sprintf("%03d_%s.rb", id, safe_name))

      # 写入文件（单独 try，确保即使失败也不影响主循环）
      begin
        file = File.open(out_path, "wb")
        file.write(content)
        file.close
        safe_puts "✅ Exported: #{name} -> #{safe_name}"
      rescue => e2
        safe_puts "⚠️  File write failed for '#{safe_name}': #{e2.class} - #{e2.message}"
      end

    rescue => e
      safe_puts "⚠️  Export failed for script '#{name}': #{e.class} - #{e.message}"
    end
  end
end

safe_puts "All scripts exported successfully to '#{output_dir}/'"
